package middle

import (
	"github.com/gin-gonic/gin"
	"lisGin/lib"
	"lisGin/server"
	"net/http"
)

func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取header中的token
		tokenStr := c.Request.Header.Get("Authorization")
		if tokenStr == "" {
			msg := lib.Fail(lib.TokenErrorCode, lib.TokenErrorMsg)
			c.AbortWithStatusJSON(http.StatusUnauthorized, msg)
			return
		}
		// 解析验证token
		_, err := lib.ParseToken(tokenStr, server.AppSecretKey)
		if err != nil {
			msg := lib.Fail(lib.TokenErrorCode, lib.TokenErrorMsg)
			c.AbortWithStatusJSON(http.StatusUnauthorized, msg)
			return
		}
		c.Next()
	}
}
